package com.qztc.hire_end_core.controller;

import com.qztc.hire_end_core.config.VerifyCodeConfig;
import com.qztc.hire_end_core.enums.RedisCache;
import com.qztc.hire_end_core.enums.RespBean;
import com.qztc.hire_end_core.util.CodeUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.codehaus.plexus.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/verify")
@Tag(name = "验证码生成接口")
public class VerifyCodeController {

    // 注入配置类和Redis缓存
    @Autowired
    private VerifyCodeConfig verifyCodeConfig;
    @Autowired
    private RedisCache redisCache;  // 若RedisCache是自定义缓存工具，需确保已正确注入

    @Operation(summary = "生成验证码")
    @GetMapping("/generateVerifyCode")
    public RespBean generateVerifyCode() {
        Map<String, Object> map = new HashMap<>();
        // 生成验证码图片和字符串（依赖CodeUtils工具类，需确保可访问）
        Object[] objects = CodeUtils.createImage();
        // 验证码字符串转小写
        String codeStr = objects[0].toString().toLowerCase();
        // 验证码图片对象
        BufferedImage codeImg = (BufferedImage) objects[1];
        // 生成图片唯一标识codeKey
        String codeKey = System.currentTimeMillis() + "";
        // 构造Redis缓存Key（前缀+codeKey）
        String cacheKey = verifyCodeConfig.getPrefix() + codeKey;
        // 存入Redis（设置过期时间）
        redisCache.setCacheObject(cacheKey, codeStr, verifyCodeConfig.getTimeout(), TimeUnit.SECONDS);

        // 图片转Base64字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(codeImg, verifyCodeConfig.getType(), baos);
        } catch (IOException e) {
            e.printStackTrace();
            return RespBean.error(e.getMessage());
        }
        byte[] base64Bytes = Base64.encodeBase64(baos.toByteArray());
        String codePic =new String(base64Bytes);

        // 封装返回数据（codeKey和Base64图片）
        map.put("codeKey", codeKey);
        map.put("codePic", codePic);
        return RespBean.ok("验证码生成成功", map);
    }

    @Operation(summary = "验证验证码")
    @PostMapping("/checkVerifyCode")
    public RespBean checkVerifyCode(@RequestBody Map<String, String> map) {
        // 获取前端传递的codeKey和用户输入的验证码
        String codeKey = map.get("codeKey");
        String inputCode = map.get("inputCode");
        // 构造Redis缓存Key
        String cacheKey = verifyCodeConfig.getPrefix() + codeKey;
        // 从Redis获取缓存的验证码
        String cacheValue = redisCache.getCacheObject(cacheKey);

        // 验证逻辑（非空且忽略大小写匹配）
        if (Objects.nonNull(cacheValue) && cacheValue.equalsIgnoreCase(inputCode)) {
            return RespBean.ok("验证码匹配成功");
        }
        return RespBean.error("验证码匹配失败");
    }
}
